package com.qf.java2106.huangshengrui.hotel.controller.backend;

import com.qf.java2106.huangshengrui.hotel.common.ResultVO;
import com.qf.java2106.huangshengrui.hotel.constant.MethodConstant;
import com.qf.java2106.huangshengrui.hotel.controller.BaseServlet;
import com.qf.java2106.huangshengrui.hotel.factory.BeanFactory;
import com.qf.java2106.huangshengrui.hotel.service.ITableService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 餐桌
 * @author q
 * @version V1.0
 * @date 2021/10/30
 **/
@WebServlet("/table")
public class TableController extends BaseServlet {

    ITableService tableService = (ITableService) BeanFactory.getBean("tableService");

    /**
     * 判断用户权限
     * @param request
     * @param response
     * @return true为管理员
     * @throws IOException
     * @throws ServletException
     */
    public boolean checkUser(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        Integer userIsAdmin = (Integer) request.getSession().getAttribute("userIsAdmin");
        if (userIsAdmin == 1){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据key查找餐桌
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public String search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        boolean b = checkUser(request, response);
        if (!b){
            return "<script>alert('您不是管理员，无权操作~');alert('请点击右侧退出重新登陆~');</script>";
        }
        String keyword = request.getParameter("keyword");
        ResultVO allTable = tableService.findAllTable();
        ResultVO vo = tableService.findTableLikeKey(keyword);
        if (allTable.getSuccess()){
            request.getSession().setAttribute("allTable",allTable.getData());
        } else {
            return (String) allTable.getData();
        }
        if (vo.getSuccess()){
            request.setAttribute("tableList",vo.getData());
            request.setAttribute("keyword",keyword);
            return MethodConstant.FORWARD_PREFIX + request.getContextPath()+"/backend/detail/table/table-list.jsp";
        } else {
            return (String) vo.getData();
        }
    }

}
